// 加载模块
const db = require('../db');
const utils = require('utility');
// 这个文件， 存放 个人中心相关的接口（获取用户信息，更新用户信息，重置密码，更换头像）
const express = require('express');
const router = express.Router();
router.use(express.urlencoded({ extended:false }));

// ----------------------------- 获取用户信息 -----------------------
router.get('/userinfo',(req,res) =>{
    db('select * from user where id=?',req.user.id,(err,result) =>{
        if(err) throw err;
        res.send({
            status:0,
            message:'获取用户信息成功',
            data: result[0]
        })
    })
})
// ----------------------------- 更新用户信息 -----------------------
router.post('/userinfo',(req,res) =>{
    let nickname = req.body.nickname;
    let email = req.body.email;
    let id = req.user.id;
    db('update user set nickname=?, email=? where id=?',[nickname,email,id],(err,result)=>{
        if(err) throw err;
        res.send({
            status:0,
            message:'更新用户信息成功'
        })
    })
})
// ----------------------------- 重置密码 -----------------------
router.post('/updatepwd',(req,res) =>{
    let id = req.user.id;
    let password =utils.md5(req.body.password);
    db('select password from user where id=?',req.user.id,(err,result) =>{
        if(err) throw err;
        // console.log(result);
        if(result.password===password){
            res.send({
                status:1,
                message:'新密码不能和原密码相同'
            });
        }else{
            db('update user set password=? where id=?',[password,id],(err,result) =>{
                if(err) throw err;
                res.send({
                    status:0,
                    message:'修改密码成功'
                });
            });
        }
    });
});
// ----------------------------- 更换头像 -----------------------
router.post('/update/avatar',(req,res) =>{
   let user_pic= req.body.user_pic;
   let id = req.user.id;
    db('update user set user_pic=? where id=?',[user_pic,id],(err,result) =>{
        if(err) throw err;
        res.send({
            status:0,
            message:'更换头像成功'
        });
    });
});
module.exports = router;